<?php
/**
 * Admin Groups Controller
 *
 * This handles all AJAX requests from the Admin GUI Group page.
 * These methods will create an AJAX response containing JSON data. The JSON
 * data is read by the JS code and rendered into interface.
 *
 * @access 	public
 * @author 	Valentin
 * @copyright	ResMania 2009 all rights reserved.
 * @link		http://developer.resmania.com/api
 */
class RM_Admin_Groups_ListController extends RM_Controller
{
    /**
     * Returns a JSON list to present groups rows on the admin end.
     * All params gets from Request
     *
     * @param start - SQL offset to implement pagination
     * @param limit - SQL count, number of rows on one page
     * @param sort - field name for sorting, if 'name' given sorting will be for current ISO selected
     * @param dir - diresction of sorting: DESC or ASC
     * @return stdClass object
     */
    function listJsonAction(){
        $iso = RM_Environment::getInstance()->getLocale();
        $offset = $this->_getParam('start');
        $count = $this->_getParam('limit');
        $sort = $this->_getParam('sort', 'id');
        if ($sort == 'name') {
            $sort = $iso;
        }
        $direction = $this->_getParam('dir', 'DESC');

        $order = $sort . ' ' . $direction;
        $dao = new RM_Groups();

        $total = $dao->filterAll($order)->count();
        $rows = $dao->filterAll($order, $count, $offset);

        $unitsModel = new RM_Units();
        $data = array();
        foreach ($rows as $row) {
            $dataRow = $row->toArray();
            if ($row->main_unit_id !== null) {
                $unit = $unitsModel->get($row->main_unit_id, $iso);
                $dataRow['unit_name'] = $unit->name;
            } else {
                $dataRow['unit_name'] = '';
            }
            $dataRow['name'] = $dataRow[$iso];
            $data[] = $dataRow;
        }

        $json = new stdClass;
        $json->total = $total;
        $json->data = $data;

        return array(
            'data' => $json
        );
    }

    /**
     * Ajax action method to delete groups
     *
     * @param ids - array from request with ids of groupds that need to be deleted
     * @return stdClass object
     */
    public function deleteJsonAction()
    {
        $ids = $this->_getParam('ids', array());
        $model = new RM_Groups();

        foreach ($ids as $id) {
            $row = $model->find($id)->current();
            if ($row === null) {
                continue;
            }
            $row->delete();
        }

        return array(
            'data' => array('success' => true)
        );
    }
}